using System;
using System.IO;
using System.Text;

namespace NFreeMarker.Core
{
    /**
     * This exception is thrown when parse errors are encountered.
     * You can explicitly create objects of this exception type by
     * calling the method generateParseException in the generated
     * parser.
     *
     * You can modify this class to customize your error reporting
     * mechanisms so long as you retain the public fields.
     */

    public class ParseException : IOException
    {
        /**
         * This constructor is used by the method "generateParseException"
         * in the generated parser.  Calling this constructor generates
         * a new object of this type with the fields "currentToken",
         * "expectedTokenSequences", and "tokenImage" set.  The boolean
         * flag "specialConstructor" is also set to true to indicate that
         * this constructor was used to create this object.
         * This constructor calls its super class with the empty string
         * to force the "toString" method of parent class "Throwable" to
         * print the error message in the form:
         *     ParseException: <result of getMessage>
         */
        public ParseException(
            Token currentTokenVal,
            long[][] expectedTokenSequencesVal,
            string[] tokenImageVal)
            : base("")
        {
            SpecialConstructor = true;
            CurrentToken = currentTokenVal;
            ExpectedTokenSequences = expectedTokenSequencesVal;
            TokenImage = tokenImageVal;
        }

        /**
         * The following constructors are for use by you for whatever
         * purpose you can think of.  Constructing the exception in this
         * manner makes the exception behave in the normal way - i.e., as
         * documented in the class "Throwable".  The fields "errorToken",
         * "expectedTokenSequences", and "tokenImage" do not contain
         * relevant information.  The JavaCC generated code does not use
         * these constructors.
         */
        internal ParseException()
        {
            SpecialConstructor = false;
        }

        /*
          public ParseException(string message) {
            super(message);
            specialConstructor = false;
          }
        */

        public ParseException(string message, int lineNumber, int columnNumber)
            : base(message)
        {
            SpecialConstructor = false;
            LineNumber = lineNumber;
            ColumnNumber = columnNumber;
        }

        public ParseException(string message, TemplateObject tobj)
            : base(message)
        {
            SpecialConstructor = false;
            LineNumber = tobj.GetBeginLine();
            ColumnNumber = tobj.GetBeginColumn();
        }

        /**
         * This variable determines which constructor was used to create
         * this object and thereby affects the semantics of the
         * "getMessage" method (see below).
         */
        protected bool SpecialConstructor;

        /**
         * This is the last token that has been consumed successfully.  If
         * this object has been created due to a parse error, the token
         * following this token will (therefore) be the first error token.
         */
        public Token CurrentToken;

        public int ColumnNumber, LineNumber;

        /**
         * Each entry in this array is an array of integers.  Each array
         * of integers represents a sequence of tokens (by their ordinal
         * values) that is expected at this point of the parse.
         */
        public long[][] ExpectedTokenSequences;

        /**
         * This is a reference to the "tokenImage" array of the generated
         * parser within which the parse error occurred.  This array is
         * defined in the generated ...Constants interface.
         */
        public string[] TokenImage;

        private string _templateName = "unknown template";

        public void SetTemplateName(string templateName)
        {
            _templateName = templateName;
        }

        /**
         * This method has the standard behavior when this object has been
         * created using the standard constructors.  Otherwise, it uses
         * "currentToken" and "expectedTokenSequences" to generate a parse
         * error message and returns it.  If this object has been created
         * due to a parse error, and you do not catch it (it gets thrown
         * from the parser), then this method is called during the printing
         * of the final stack trace, and hence the correct error message
         * gets displayed.
         */
        public override string Message
        {
            get
            {
                if (!SpecialConstructor)
                {
                    return base.Message + " in " + _templateName;
                }
                string retval = CustomGetMessage();
                if (retval != null)
                {
                    return retval;
                }
                // The default JavaCC message generation stuff follows.
                string expected = "";
                int maxSize = 0;
                foreach (long[] sequence in ExpectedTokenSequences)
                {
                    if (maxSize < sequence.Length)
                    {
                        maxSize = sequence.Length;
                    }
                    for (int j = 0; j < sequence.Length; j++)
                    {
                        expected += TokenImage[sequence[j]] + " ";
                    }
                    if (sequence[sequence.Length - 1] != 0)
                    {
                        expected += "...";
                    }
                    expected += eol + "    ";
                }
                retval = "Encountered \"";
                Token tok = CurrentToken.next;
                for (int i = 0; i < maxSize; i++)
                {
                    if (i != 0) retval += " ";
                    if (tok.kind == 0)
                    {
                        retval += TokenImage[0];
                        break;
                    }
                    retval += AddEscapes(tok.image);
                    tok = tok.next;
                }
                retval += "\" at line " + CurrentToken.next.beginLine + ", column " + CurrentToken.next.beginColumn;
                retval += " in " + _templateName + "." + eol;
                if (ExpectedTokenSequences.Length == 1)
                {
                    retval += "Was expecting:" + eol + "    ";
                }
                else
                {
                    retval += "Was expecting one of:" + eol + "    ";
                }
                retval += expected;
                return retval;
            }
        }

        public int GetLineNumber()
        {
            return CurrentToken != null ?
                                   CurrentToken.next.beginLine :
                                   LineNumber;
        }

        public int GetColumnNumber()
        {
            return CurrentToken != null ?
                                   CurrentToken.next.beginColumn :
                                   ColumnNumber;
        }

        // Custom message generation

        private string CustomGetMessage()
        {
            Token nextToken = CurrentToken.next;
            int kind = nextToken.kind;
            if (kind == FMParserConstants.EOF)
            {
                var buf = new StringBuilder("Unexpected end of file reached.\n");
                foreach (long[] sequence in ExpectedTokenSequences)
                {
                    switch (sequence[0])
                    {
                        case FMParserConstants.END_FOREACH:
                            buf.Append("Unclosed foreach directive.\n");
                            break;
                        case FMParserConstants.END_LIST:
                            buf.Append("Unclosed list directive.\n");
                            break;
                        case FMParserConstants.END_SWITCH:
                            buf.Append("Unclosed switch directive.\n");
                            break;
                        case FMParserConstants.END_IF:
                            buf.Append("Unclosed if directive.\n");
                            break;
                        case FMParserConstants.END_COMPRESS:
                            buf.Append("Unclosed compress directive.\n");
                            break;
                        case FMParserConstants.END_MACRO:
                            buf.Append("Unclosed macro directive.\n");
                            break;
                        case FMParserConstants.END_FUNCTION:
                            buf.Append("Unclosed function directive.\n");
                            break;
                        case FMParserConstants.END_TRANSFORM:
                            buf.Append("Unclosed transform directive.\n");
                            break;
                        case FMParserConstants.END_ESCAPE:
                            buf.Append("Unclosed escape directive.\n");
                            break;
                        case FMParserConstants.END_NOESCAPE:
                            buf.Append("Unclosed noescape directive.\n");
                            break;
                    }
                }
                return buf.ToString();
            }
            if (kind == FMParserConstants.END_IF || kind == FMParserConstants.ELSE_IF || kind == FMParserConstants.ELSE)
            {
                return "Found unexpected directive: "
                    + nextToken
                    + " on line " + nextToken.beginLine
                    + ", column " + nextToken.beginColumn
                    + "\nCheck whether you have a well-formed if-else block.";
            }
            return null;
        }

        /**
         * The end of line string for this machine.
         */
        protected string eol = System.Environment.NewLine;

        /**
         * Used to convert raw characters to their escaped version
         * when these raw version cannot be used as part of an ASCII
         * string literal.
         */
        protected static string AddEscapes(string str)
        {
            var retval = new StringBuilder();
            char ch;
            for (int i = 0; i < str.Length; i++)
            {
                switch (str[i])
                {
                    // TODO: case 0:
                    //    continue;
                    case '\b':
                        retval.Append("\\b");
                        continue;
                    case '\t':
                        retval.Append("\\t");
                        continue;
                    case '\n':
                        retval.Append("\\n");
                        continue;
                    case '\f':
                        retval.Append("\\f");
                        continue;
                    case '\r':
                        retval.Append("\\r");
                        continue;
                    case '\"':
                        retval.Append("\\\"");
                        continue;
                    case '\'':
                        retval.Append("\\\'");
                        continue;
                    case '\\':
                        retval.Append("\\\\");
                        continue;
                    default:
                        if ((ch = str[i]) < 0x20 || ch > 0x7e)
                        {
                            string s = "0000" + Convert.ToString(ch, 16);
                            retval.Append("\\u" + s.Substring(s.Length - 4, 4));
                        }
                        else
                        {
                            retval.Append(ch);
                        }
                        continue;
                }
            }
            return retval.ToString();
        }
    }
}